<template>
  <view class="container" :style="{ paddingTop: statusBarHeight + 'px' }">
    <uni-nav-bar title="盘点" fixed :border="false" height="88rpx" left-icon="left" @clickLeft="onClickLeft"></uni-nav-bar>
    <view class="topCard">
      <uni-search-bar v-model="name" radius="100" placeholder="请输入名称或一维码" cancelButton="none"
        style="flex: 1;margin: 0;padding: 0;margin-right: 20rpx;" @confirm="searchFn" @clear="clearFn" />
    </view>
    <scroll-view style="height: calc(100% - var(--window-top) - 168rpx);box-sizing: border-box;"
      :style="{ paddingBottom: `calc(${safeAreaBottom}px + 80rpx	)` }" scroll-y enhanced :show-scrollbar="false"
      @scrolltolower="lower" :scroll-with-animation="true" refresher-enabled @refresherrefresh="pulldownRefresh"
      :refresher-triggered="triggered" @touchmove.stop>
      <view class="list" v-if="ordergoodsList.length > 0">
        <view class="item" v-for="(item, index) in ordergoodsList" :key="item.id + index">
          <view class="flexBox">
            <view class="sub_title u-ellipsis">{{ item.name }}</view>
            <view class="sub_title u-ellipsis">{{ item.barCode }}</view>
          </view>
          <view class="flexBox">
            <view style="width: 50%;">库存：{{ item.inventoryNum }}</view>
            <view style="width: 35%;display: flex;">盘点数量：{{ item.stocktakingNum ? item.stocktakingNum : 0 }}</view>
            <view style="width: 15%;display: flex;">
              <uni-icons type="compose" size="24" @click="editFn(item)" style="color: #007aff;"></uni-icons>
            </view>
          </view>
          <view class="flexBox">
            <view class="sub_title1" v-if="item.status == '0'">状态：<text style="color: rgb(3, 199, 3);">正常</text></view>
            <view class="sub_title1" v-if="item.status == '1'">状态：<text style="color: rgb(8, 117, 206);">盘盈</text></view>
            <view class="sub_title1" v-if="item.status == '2'">状态：<text style="color: rgb(177, 30, 4);">盘亏</text></view>
            <view class="sub_title1" v-if="item.status == '3'">状态：<text style="color: rgb(81, 83, 81);">未盘</text></view>
          </view>
        </view>
      </view>
      <uni-load-more :status="loading" v-if="ordergoodsList.length > 0"></uni-load-more>
      <view
        style="width: 100%;height: 100%;background-color: #f7f7f7;display: flex;justify-content: center;align-items: center;"
        v-if="ordergoodsList.length == 0">
        <image src="/static/index/nonedata.png" mode="aspectFill" style="width: 400rpx;height: 400rpx;"></image>
      </view>
    </scroll-view>
    <view v-if="!name" class="bottomFix" @click="submitOrder" :style="{ paddingBottom: safeAreaBottom + 'px' }">
      <text class="btnBox">确 认 提 交</text>
    </view>

    <uni-popup ref="inputDialog" type="dialog">
      <uni-popup-dialog ref="inputClose" mode="input" title="修改盘点数量" @confirm="submit" @close="close" before-close>
        <template>
          <uni-forms ref="form" :model="formData" :rules="rules" label-width="50" validate-trigger="blur">
            <uni-forms-item label="数量:" name="stocktakingNum">
              <uni-easyinput type="number" v-model="formData.stocktakingNum" focus placeholder="请输入盘点数量"
                :clearable="false" trim="all" adjust-position />
            </uni-forms-item>
            <uni-forms-item label="备注:" name="remark">
              <uni-easyinput type="text" v-model="formData.remark" placeholder="请输入备注" :clearable="false" trim="all"
                adjust-position />
            </uni-forms-item>
          </uni-forms>
        </template>
      </uni-popup-dialog>
    </uni-popup>
    <uni-popup ref="inputDialog2" type="dialog">
      <uni-popup-dialog ref="inputClose" mode="input" title="提交盘点记录" @confirm="submitLast" @close="closeLast"
        before-close>
        <template>
          <uni-forms ref="form2" :model="formData2" :rules="rules2" label-width="100" validate-trigger="blur">
            <uni-forms-item label="盘点名称:" name="name">
              <uni-easyinput type="text" v-model="formData2.name" focus placeholder="请输入盘点名称" :clearable="false"
                trim="all" adjust-position />
            </uni-forms-item>
            <uni-forms-item label="备注:" name="remark">
              <uni-easyinput type="text" v-model="formData2.remark" placeholder="请输入备注" :clearable="false" trim="all"
                adjust-position />
            </uni-forms-item>
            <view class="infoRemark">请确认盘点信息准确无误后再进行提交，提交后将修改商品库存数量。</view>
          </uni-forms>
        </template>
      </uni-popup-dialog>
    </uni-popup>
  </view>
</template>

<script>
import { reqStockList, reqCreateSelfStock, reqUpdateStock } from '@/apis/goods'
export default {
  name: "NoWaitSubmit",
  data() {
    return {
      balance: 0,
      name: '',
      ordergoodsList: [],
      triggered: false,
      oldordergoodsList: [],
      totalMoney: 0,
      loading: 'loading',
      page: {
        pageNum: 1,
        pageSize: 15
      },
      formData: {
        stocktakingNum: null,
        remark: '',
        id: ''
      },
      rules: {
        // 对name字段进行必填验证
        stocktakingNum: {
          rules: [{
            required: true,
            errorMessage: '请输入盘点数量',
          },
          {
            validateFunction: function (rule, value, data, callback) {
              let reg = /^[0-9]\d*$/
              if (!reg.test(value)) {
                callback('请输入数字')
              }
            }
          }
          ],
        }
      },
      formData2: {
        name: '',
        remark: ''
      },
      rules2: {
        name: {
          rules: [{
            required: true,
            errorMessage: '请输入盘点名称',
          }],
        }
      },
    }
  },
  // watch: {
  //   ordergoodsList: {
  //     handler(val) {
  //       if (val.stocktakingNum == 0) {
  //         val.status = '3' // 未盘
  //       } else if (val.inventoryNum < val.stocktakingNum) {
  //         val.status = '1' // 盘盈
  //       } else if (val.inventoryNum > val.stocktakingNum) {
  //         val.status = '2' // 盘亏
  //       } else if (val.stocktakingNum == val.inventoryNum) {
  //         val.status = '0' // 正常
  //       }
  //       console.log('val', val);
  //     },
  //     immediate: true,
  //     deep: true
  //   }
  // },
  onShow() {
    this.reqStockList()
  },
  methods: {
    async reqStockList() {
      const res = await reqStockList({ ...this.page, name: this.name })
      if (res.code === 200) {
        this.triggered = false
        // const arr = this.ordergoodsList.map(item => item)
        this.ordergoodsList = [...this.ordergoodsList, ...res.data.list]
        console.log('res.data.ordergoodsList11111', this.ordergoodsList);
        if (res.data.isLastPage) {
          this.loading = "noMore"
        } else {
          this.loading = "loading"
        }
      }
    },
    pulldownRefresh() {
      this.triggered = true
      this.ordergoodsList = []
      this.reqStockList()
    },
    submitOrder() {
      this.$refs.inputDialog2.open();
    },
    async submitLast() {
      if (this.ordergoodsList.length === 0) {
        uni.utils.toast('请先添加盘点商品');
        return
      }
      this.$refs.form2.validate().then(async (suc) => {
        const res = await reqCreateSelfStock({
          ...this.formData2
        })
        if (res.code === 200) {
          this.$refs.inputDialog2.close();
          uni.showToast({
            title: '提交成功',
            icon: 'success',
            duration: 1000
          })
          setTimeout(() => {
            uni.navigateBack({
              delta: 2
            });
          }, 1000)
          // 返回

        }
      })
    },
    closeLast() {
      this.$refs.inputDialog2.close();
    },
    async searchFn() {
      this.page.pageNum = 1
      this.ordergoodsList = []
      this.reqStockList()
    },
    lower() {
      if (this.loading == "noMore") {
        console.log('no');
        return;
      }
      this.page.pageNum++;
      this.loading = "loading";
      this.reqStockList()
    },
    editFn(row) {
      this.$refs.inputDialog.open();
      console.log('row', row);
      this.formData = {
        stocktakingNum: row.stocktakingNum ? row.stocktakingNum : 0,
        id: row.id,
        remark: row.remark
      };
    },
    async submit() {
      this.$refs.form.validate().then(async (suc) => {
        const res = await reqUpdateStock({ ...this.formData })
        if (res.code === 200) {
          this.page.pageNum = 1
          this.ordergoodsList = []
          this.reqStockList()
          this.close()
        }
      })
    },
    close() {
      this.formData = {
        stocktakingNum: null,
        id: '',
        remark: ''
      };
      this.$refs.inputDialog.close();
      console.log("关闭");
    },
    clearFn() {
      this.page.pageNum = 1
      this.ordergoodsList = []
      this.reqStockList()
    }
  }
}
</script>

<style>
page {
  background: #f7f7f7;

}
</style>
<style lang="scss" scoped>
view {
  box-sizing: border-box;
}

.container {
  height: 100vh;
}

.topCard {
  font-size: 26rpx;
  height: 80rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20rpx;
  // background-color: #fff;
  border: 1px solid #eee;
}

.list {
  padding: 20rpx 20rpx;
  padding-bottom: 0;

  .item {
    padding: 20rpx 24rpx;
    background-color: #fff;
    border-radius: 8rpx;
    margin-bottom: 20rpx;

    &:last-child {
      margin-bottom: 0;
    }

    .flexBox {
      display: flex;
      justify-content: space-between;
      margin-bottom: 30rpx;

      .sub_title {
        width: 45%;
      }

      .sub_title1 {
        width: 100%;
      }
    }
  }
}

.bottomFix {
  position: fixed;
  width: 100%;
  height: 80rpx;
  bottom: 0;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: $uni-font-size-base;

  .btnBox {
    width: 100%;
    text-align: center;
    height: 80rpx;
    line-height: 80rpx;
    background-color: $uni-main-bgColor;
    color: #fff;
  }

  .btnBox:nth-child(2) {
    background-color: #fff;
    color: #000;
  }
}

.infoRemark {
  font-size: 28rpx;
  color: red
}
</style>